package com.kele.base.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GenericTypeUtil {

    /**
     * 获取泛型参数的class对象
     * @param cls 当前类的class
     * @param index 泛型参数下标
     * @return 泛型参数的class对象
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getParameterizedClass(Class<?> cls, int index) {
        Type type = cls.getGenericSuperclass();
        do {
            if (type instanceof ParameterizedType parameterizedType) {
                return (Class<T>) parameterizedType.getActualTypeArguments()[index];
            } else if (type instanceof Class<?> cls2) {
                type = cls2.getGenericSuperclass();
            } else {
                throw new IllegalStateException("无法实体信息类型！" + cls);
            }
        } while (true);
    }
}
